use super::models::{ScriptInfo, TagInfo, TemplateInfo};

pub struct VueParser {}

impl<'a> TemplateInfo<'a> {
    pub fn get_cli_tag(&self, tag_name: &str) -> Option<TagInfo> {
        let start_tag = &format!("<!--cli:{}", tag_name);
        let end_tag = &format!("<!--/cli:{}-->", tag_name);

        let start_index = self.content.find(start_tag)?;
        let end_index = self.content[start_index..].find(end_tag)?;
        let inner_start_index = self.content[start_index..].find('>')?;

        Some(TagInfo {
            start_index: self.content_start_index + start_index,
            end_index: self.content_start_index + start_index + end_index + end_tag.len(),
            inner_start_index: self.content_start_index + start_index + inner_start_index + 1,
            inner_end_index: self.content_start_index + start_index + end_index,
        })
    }
    pub fn set_tag_content(&self, tag: Option<&TagInfo>, content: &str) -> Option<String> {
        tag.map(|tag1| {
            format!(
                "{}{}{}",
                &self.origin_content[..tag1.inner_start_index],
                content,
                &self.origin_content[tag1.inner_end_index..]
            )
        })
    }
}

impl VueParser {
    const TEMPLATE_START_TAG: &'static str = "<template>";
    const TEMPLATE_END_TAG: &'static str = "</template>";
    const SCRIPT_START_TAG: &'static str = "<script>";
    const SCRIPT_END_TAG: &'static str = "</script>";

    pub fn get_template(content: &str) -> Option<TemplateInfo> {
        match (
            content.find(Self::TEMPLATE_START_TAG),
            content.find(Self::TEMPLATE_END_TAG),
        ) {
            (Some(start), Some(end)) => Some(TemplateInfo {
                start_index: start,
                end_index: end + Self::TEMPLATE_END_TAG.len(),
                content_start_index: start + Self::TEMPLATE_START_TAG.len(),
                content_end_index: end,
                content: &content[start + Self::TEMPLATE_START_TAG.len()..end],
                origin_content: content,
            }),
            _ => None,
        }
    }
    pub fn get_script(content: &str) -> Option<ScriptInfo> {
        match (
            content.find(Self::SCRIPT_START_TAG),
            content.find(Self::SCRIPT_END_TAG),
        ) {
            (Some(start), Some(end)) => Some(ScriptInfo {
                start_index: start,
                end_index: end + Self::SCRIPT_END_TAG.len(),
                inner_start_index: start + Self::SCRIPT_START_TAG.len(),
                inner_end_index: end,
                origin_content: content,
            }),
            _ => None,
        }
    }
}
